package com.game.centerserver.utils;

import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class JsonClient<T> {

    public T get(String ip, Integer port, String url, Map<String, String> params, Class<T> responseType) {
        RestTemplate restTemplate = new RestTemplate();
        T data = null;

        String URL = "http://" + ip + ":" + port + "/" + url;
        
        // 设置请求头（可选）
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer your_token_here");
        HttpEntity<String> entity = new HttpEntity<>(headers);
        
        // 发送GET请求并接收JSON响应
        ResponseEntity<T> response = restTemplate.exchange(
            URL,
            HttpMethod.GET,
            entity,
            responseType // 指定返回类型
        );

        // 处理响应
        if (response.getStatusCode().is2xxSuccessful()) {
            data = response.getBody();
            System.out.println("get success: " + URL);
        } else {
            System.err.println("get failed " + URL + " retrieve data, status code: " + response.getStatusCode());
        }

        return data;
    }

    public T post(String ip, Integer port, String url, Map<String, String> params, Object request, Class<T> responseType) {
        RestTemplate restTemplate = new RestTemplate();
        T data = null;

        String URL = "http://" + ip + ":" + port + "/" + url;
        
        // 设置请求头（可选）
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        HttpEntity<Object> entity = new HttpEntity<>(request, headers);

        // 发送GET请求并接收JSON响应
        ResponseEntity<T> response = restTemplate.exchange(
            URL,
            HttpMethod.POST,
            entity,
            responseType // 指定返回类型
        );

        // 处理响应
        if (response.getStatusCode().is2xxSuccessful()) {
            data = response.getBody();
            System.out.println("post success: " + URL);
        } else {
            System.err.println("post failed " + URL + " retrieve data, status code: " + response.getStatusCode());
        }

        return data;
    }
}